package com.strival.bal.service;

import com.strival.bal.api.UserService;
import com.strival.bal.dto.UserBaseInfo;
import com.strival.bal.exception.BizException;
import com.strival.bal.utils.MD5;
import com.strival.dal.dao.UserDao;
import com.strival.dal.po.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class UserServiceImpl implements UserService{

    private static Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);

    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public UserBaseInfo validate(String username, String password) throws BizException {
        User user=userDao.findByUsername(username);

        if(user!=null){
            if(user.getPassword().equals(MD5.encode(password))){
                return new UserBaseInfo().setId(user.getId()).setUsername(user.getUsername());
            }else{
                throw new BizException(BizException.ERROR_CODE_PASSWORD_ERROR,"validate user , password error");
            }
        }else{
            throw new BizException(BizException.ERROR_CODE_USER_NOT_FOUND,"validate user , not found user");
        }
    }

    @Override
    public void updatePassword(long userId, String oldPassword, String newPassword) throws BizException {

    }

    @Override
    public UserBaseInfo addUser(String username, String password) throws BizException {
        User user=userDao.findByUsername(username);

        if(user == null){
            user=new User();
            user.setUsername(username);
            user.setPassword(MD5.encode(password));

            return new UserBaseInfo().setUsername(username);
        }else{
            throw new BizException(BizException.ERROR_CODE_USERNAME_EXISTED,"add user , username existed");
        }
    }
}
